﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;

namespace BerkeleyAlgorithm
{
    class tcpServer
    {
        public Socket socket;
        TcpListener tcpListener;

        
        public tcpServer(IPAddress ipAddress, int port)
        {

            try
            {

                // IPAddress ipAddress = IPAddress.Parse(ip); //use local m/c IP address, and use the same in the client
                /* Initializes the Listener */
                tcpListener = new TcpListener(ipAddress, port);
                /* Start Listeneting at the specified port */
                tcpListener.Start();
                Console.WriteLine("The server is running at port 8001...");
                Console.WriteLine("The local End point is :" + tcpListener.LocalEndpoint);
                Console.WriteLine("Waiting for a connection.....");              
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }

        public byte[] listenAndGetMsg()
        {           
            byte[] msg=null;
            System.Threading.Thread newThread;
            newThread = new System.Threading.Thread(() => { msg = getMsg(); });
            newThread.IsBackground = true;
            newThread.Start();
            newThread.Join();

            return msg;
        }
                
        public void exit()
        {
            tcpListener.Stop();
            socket.Close();
        }

        public byte[] getMsg()
        {
            Console.WriteLine("getting msg from "+tcpListener.ToString());
            socket = tcpListener.AcceptSocket();
            byte[] word = new byte[100];
            int k = socket.Receive(word);
                        
            for (int i = 0; i < k; i++)
                Console.Write(Convert.ToChar(word[i]));

            Console.WriteLine("got "+word);
            return word;
        }
              

        public void sengMsg(string str)
        {
            Console.WriteLine("sending "+str);
            ASCIIEncoding asen = new ASCIIEncoding();
            socket.Send(asen.GetBytes(str));
            Console.WriteLine("gmsg sent");
        }        
    }
}
